const nodemailer = require("nodemailer");
const schedule = require("node-schedule");
const { getList } = require("../utils/sql");

let transporter = nodemailer.createTransport({
  service: "QQ",
  port: 465,
  secure: true,
  auth: {
    user: "1029708622@qq.com",
    pass: "mcawyzchkvpcbajb",
  },
});

let mainOptions = {
  from: "沈嘉宁🌲👻 <1029708622@qq.com>", // 发送者昵称和地址
  to: "1029708622@qq.com", // 接收者的邮箱地址
  subject: "今日未完成计划",
  html: "",
};

function getToday() {
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();

  let completeDay = `${year}-${("0" + month).slice(-2)}-${("0" + day).slice(
    -2
  )}`;
  return completeDay;
}
async function getReceiveInfo() {
  let result = await getList("user");
  let userList = result.filter((item) => item.email);
  userList.forEach((user) => sendEmail(user));
}

async function sendEmail(user) {
  let today = getToday();
  let result = await getList(
    "daily_task",
    ["date", "user_id", "status"],
    [today, user.user_id, 0]
  );
  if (result.length === 0) return;
  mainOptions.to = user.email;
  for (let i = 0; i < result.length; i++) {
    mainOptions.html += `${i + 1}、${result[i].content}；<br/>`;
  }
  transporter.sendMail(mainOptions, (error, info) => {
    if (error) return;
    console.log("发送成功", info.messageId);
  });
}

schedule.scheduleJob("0 0 20 * * *", () => {
  getReceiveInfo();
});
